package com.uyayo.oms.cms.controller;

import com.uyayo.framework.message.model.Result;
import com.uyayo.oms.cms.biz.TemplateFileBiz;
import com.uyayo.oms.cms.model.TemplateFile;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.util.List;

/**
 * Created by hfj
 * on 2017/8/20.
 */
@Controller
@RequestMapping("/cms/template")
public class CmsTemplateController {

    private final TemplateFileBiz templateFileBiz;

    @Autowired
    public CmsTemplateController(TemplateFileBiz templateFileBiz) {
        this.templateFileBiz = templateFileBiz;
    }


    @RequiresPermissions("cms:template:admin")
    @RequestMapping
    public String index(Model model){
        List<TemplateFile> list = null;
        try {
            list = templateFileBiz.findAll();
        } catch (Exception e) {
            e.printStackTrace();
        }
        model.addAttribute("templateFiles",list);
        return "cms/template";
    }


    @RequiresPermissions("cms:template:edit")
    @RequestMapping("/input")
    public String input(TemplateFile templateFile, Model model){
        if(templateFile.getFilePath()==null)
            try {
                model.addAttribute("templateFile",templateFileBiz.findByPath(templateFile.getFilePath()));
            } catch (Exception e) {
                e.printStackTrace();
            }
        return "cms/template_input";

    }

    @RequiresPermissions("cms:template:save")
    @RequestMapping("/save")
    @ResponseBody
    public Result save(TemplateFile templateFile){
        try {
            templateFileBiz.writeTemplateFileContent(templateFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.success(200,"模板修改成功");
    }

}